<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能助手 - AI超级面试官平台</title>
    <link href="/vendors/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/fontawesome/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        /* 重置样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

                body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: #f5f7fa;
            overflow-x: hidden;
            margin: 0;
            padding: 0;
            height: 100vh;
            width: 100vw;
        }

        /* 统一导航栏样式 */
        .unified-navbar {
            background: white;
            border-bottom: 1px solid #e5e7eb;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
            height: 70px;
            width: 100%;
            margin: 0;
            padding: 0;
        }

        .unified-navbar-container {
            width: 100%;
            padding: 0 24px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .unified-navbar-left {
            flex-shrink: 0;
        }

        .unified-navbar-brand {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #1f2937;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .unified-navbar-brand i {
            color: #667eea;
            margin-right: 8px;
            font-size: 1.2rem;
        }

        .unified-navbar-brand:hover {
            color: #667eea;
            text-decoration: none;
        }

        .unified-navbar-center {
            flex: 1;
            display: flex;
            justify-content: center;
        }

        .unified-navbar-menu {
            display: flex;
            align-items: center;
            gap: 40px;
        }

        .unified-navbar-right {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .unified-nav-item {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-weight: 500;
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .unified-nav-item i {
            margin-right: 6px;
            font-size: 14px;
        }

        .unified-nav-item:hover {
            color: #667eea;
            background: #eff6ff;
            text-decoration: none;
        }

        .unified-nav-item.active {
            color: #667eea;
            background: #eff6ff;
            font-weight: 600;
        }

 

        /* 主容器 */
        .chat-app {
            display: flex;
            height: calc(100vh - 70px); /* 减去导航栏高度 */
            width: 100vw;
            background: #ffffff;
            overflow: hidden;
        }

        /* 左侧对话列表 */
        .sidebar {
            width: 320px;
            background: #ffffff;
            border-right: 1px solid #e5e7eb;
            display: flex;
            flex-direction: column;
        }

        /* 侧边栏头部 */
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e5e7eb;
            background: #ffffff;
        }

        .sidebar-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 8px;
        }

        .sidebar-subtitle {
            font-size: 14px;
            color: #6b7280;
        }

        /* 新建对话按钮 */
        .new-chat-btn {
            width: 100%;
            padding: 12px 16px;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            margin-top: 16px;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .new-chat-btn:hover {
            background: #2563eb;
        }

        /* 对话列表 */
        .chat-list {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }

        .chat-item {
            padding: 12px 16px;
            margin-bottom: 4px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            border-left: 3px solid transparent;
            position: relative;
        }

        .chat-item:hover {
            background: #f3f4f6;
        }

        .chat-item:hover .chat-item-delete {
            opacity: 1;
        }

        .chat-item.active {
            background: #eff6ff;
            border-left-color: #3b82f6;
        }

        .chat-item-title {
            font-size: 14px;
            font-weight: 500;
            color: #1f2937;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 24px; /* 为删除按钮留出空间 */
        }

        .chat-item-preview {
            font-size: 12px;
            color: #6b7280;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .chat-item-time {
            font-size: 11px;
            color: #9ca3af;
            margin-top: 4px;
        }

        .chat-item-delete {
            position: absolute;
            top: 12px;
            right: 12px;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #9ca3af;
            opacity: 0;
            transition: all 0.2s;
            border-radius: 4px;
            cursor: pointer;
        }

        .chat-item-delete:hover {
            background: #fee2e2;
            color: #dc2626;
        }

        /* 右侧聊天区域 */
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #ffffff;
            height: 100%;
            min-width: 0;
            width: calc(100vw - 320px);
        }



        /* 聊天消息区域 */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 32px 24px;
            background: #f9fafb;
            min-height: 0;
        }

        /* 欢迎界面 */
        .welcome-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            text-align: center;
            padding: 40px;
        }

        .welcome-icon {
            font-size: 4rem;
            color: #3b82f6;
            margin-bottom: 24px;
        }

        .welcome-title {
            font-size: 28px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 12px;
        }

        .welcome-subtitle {
            font-size: 16px;
            color: #6b7280;
            margin-bottom: 32px;
            max-width: 500px;
            line-height: 1.6;
        }

        .welcome-features {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            max-width: 600px;
            width: 100%;
        }

        .feature-item {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.2s;
        }

        .feature-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }

        .feature-icon {
            font-size: 2rem;
            color: #3b82f6;
            margin-bottom: 12px;
        }

        .feature-title {
            font-size: 16px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 8px;
        }

        .feature-description {
            font-size: 14px;
            color: #6b7280;
            line-height: 1.5;
        }

        .suggested-questions {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
            max-width: 500px;
        }

        .suggested-question {
            padding: 8px 16px;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 20px;
            cursor: pointer;
            font-size: 13px;
            color: #374151;
            transition: all 0.2s;
        }

        .suggested-question:hover {
            background: #3b82f6;
            color: white;
            border-color: #3b82f6;
        }

        /* 消息样式 */
        .message {
            display: flex;
            margin-bottom: 20px;
            animation: fadeInUp 0.3s ease-out;
        }
        
        /* AI消息与前一条用户消息的间距 */
        .message.ai {
            margin-top: 12px;
        }
        
        /* 当欢迎界面隐藏后，消息容器的样式 */
        .chat-messages.has-messages {
            padding-top: 40px;
        }
        
        /* 当欢迎界面隐藏后，第一条消息的样式 */
        .chat-messages.has-messages .message:first-child {
            margin-top: 0;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: 600;
            flex-shrink: 0;
            margin: 0 8px;
        }

        .message.user .message-avatar {
            background: #3b82f6;
            color: white;
        }

        .message.ai .message-avatar {
            background: #f3f4f6;
            color: #374151;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 16px;
            font-size: 14px;
            line-height: 1.5;
            word-wrap: break-word;
            word-break: break-word;
        }

        .message.user .message-content {
            background: #3b82f6;
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.ai .message-content {
            background: white;
            color: #1f2937;
            border: 1px solid #e5e7eb;
            border-bottom-left-radius: 4px;
        }

        .message-time {
            font-size: 11px;
            opacity: 0.7;
            margin-top: 4px;
        }

        /* 打字指示器 */
        .typing-indicator {
            display: none;
            align-items: center;
            gap: 8px;
            padding: 12px 16px;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            border-bottom-left-radius: 4px;
            max-width: 300px;
        }

        .typing-text {
            color: #6b7280;
            font-size: 14px;
            white-space: nowrap;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #9ca3af;
            animation: typing 1.4s infinite;
        }

        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-8px); }
        }

        /* 输入区域 */
        .chat-input {
            padding: 24px 32px;
            background: white;
            border-top: 1px solid #e5e7eb;
            box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
        }

        .input-container {
            display: flex;
            align-items: flex-end;
            gap: 16px;
            max-width: 100%;
            width: 100%;
        }

        .file-upload-area {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
            margin-top: 8px;
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .file-preview {
            width: 80px;
            height: 80px;
            border: 2px dashed #cbd5e0;
            border-radius: 8px;
            position: relative;
            background: white;
            flex-shrink: 0;
        }

        .file-info {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 8px;
        }

        .file-icon {
            font-size: 1.5rem;
            color: #3b82f6;
            margin-bottom: 4px;
        }

        .file-details {
            text-align: center;
            flex: 1;
            min-width: 0;
        }

        .file-name {
            font-size: 14px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 2px;
            word-break: break-all;
        }

        .file-size {
            font-size: 12px;
            color: #6b7280;
        }

        .remove-file-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .remove-file-btn:hover {
            background: #dc2626;
            transform: scale(1.1);
        }



        .input-row {
            display: flex;
            align-items: flex-end;
            gap: 16px;
            width: 100%;
        }

        .attachment-btn {
            background: #f8fafc;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 14px;
            font-size: 1.1rem;
            color: #6b7280;
            cursor: pointer;
            transition: all 0.3s ease;
            flex-shrink: 0;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .attachment-btn:hover {
            background: #e5e7eb;
            color: #374151;
            transform: translateY(-1px);
        }

        .attachment-btn.has-file {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: #667eea;
        }

        .message-input {
            flex: 1;
            min-height: 50px;
            max-height: 120px;
            padding: 14px 20px;
            border: 2px solid #e5e7eb;
            border-radius: 25px;
            font-size: 16px;
            font-family: inherit;
            resize: none;
            outline: none;
            transition: all 0.3s ease;
            background: #ffffff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .message-input:focus {
            border-color: #3b82f6;
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1), 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }

        .send-button {
            width: 50px;
            height: 50px;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            flex-shrink: 0;
            box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
        }

        .send-button:hover {
            background: #2563eb;
            transform: scale(1.05);
        }

        .send-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* 错误消息 */
        .error-message {
            background: #fef2f2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 280px;
            }
            
            .chat-messages {
                padding: 16px;
                height: calc(100vh - 165px); /* 保持一致的高度 */
                min-height: calc(100vh - 165px);
                max-height: calc(100vh - 165px);
            }
            
            .message-content {
                max-width: 85%;
                font-size: 13px;
            }
            
            .welcome-features {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 640px) {
            .chat-app {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: 200px;
                border-right: none;
                border-bottom: 1px solid #e5e7eb;
            }
            
            .chat-list {
                display: flex;
                overflow-x: auto;
                overflow-y: hidden;
                padding: 8px;
            }
            
            .chat-item {
                min-width: 200px;
                margin-right: 8px;
                margin-bottom: 0;
            }
        }

        /* 动画 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 滚动条样式 */
        .chat-list::-webkit-scrollbar,
        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-list::-webkit-scrollbar-track,
        .chat-messages::-webkit-scrollbar-track {
            background: #f1f5f9;
        }

        .chat-list::-webkit-scrollbar-thumb,
        .chat-messages::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .chat-list::-webkit-scrollbar-thumb:hover,
        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        /* Markdown渲染样式 */
        .message-content h1,
        .message-content h2,
        .message-content h3,
        .message-content h4,
        .message-content h5,
        .message-content h6 {
            margin: 16px 0 8px 0;
            font-weight: 600;
            line-height: 1.25;
        }

        .message-content h1 { font-size: 1.5em; }
        .message-content h2 { font-size: 1.3em; }
        .message-content h3 { font-size: 1.1em; }
        .message-content h4 { font-size: 1em; }

        .message-content p {
            margin: 8px 0;
            line-height: 1.6;
        }

        .message-content ul,
        .message-content ol {
            margin: 8px 0;
            padding-left: 20px;
        }

        .message-content li {
            margin: 4px 0;
            line-height: 1.5;
        }

        .message-content blockquote {
            margin: 12px 0;
            padding: 8px 16px;
            border-left: 4px solid #3b82f6;
            background: #f8fafc;
            font-style: italic;
        }

        .message-content code {
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            color: #e11d48;
        }

        .message-content pre {
            background: #1e293b;
            color: #f1f5f9;
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 12px 0;
            position: relative;
        }

        .message-content pre code {
            background: none;
            padding: 0;
            color: inherit;
            font-size: 0.85em;
            line-height: 1.5;
        }

        .message-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 12px 0;
            font-size: 0.9em;
        }

        .message-content th,
        .message-content td {
            border: 1px solid #e5e7eb;
            padding: 8px 12px;
            text-align: left;
        }

        .message-content th {
            background: #f9fafb;
            font-weight: 600;
        }

        .message-content strong {
            font-weight: 600;
            color: #1f2937;
        }

        .message-content em {
            font-style: italic;
            color: #6b7280;
        }

        .message-content a {
            color: #3b82f6;
            text-decoration: none;
        }

        .message-content a:hover {
            text-decoration: underline;
        }

        .message-content hr {
            border: none;
            border-top: 1px solid #e5e7eb;
            margin: 16px 0;
        }

        /* 代码块复制按钮 */
        .code-block-wrapper {
            position: relative;
        }

        .copy-code-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            background: #374151;
            color: #f9fafb;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            opacity: 0.7;
            transition: opacity 0.2s;
        }

        .copy-code-btn:hover {
            opacity: 1;
        }
    </style>
         <!-- 引入必要的JavaScript库 -->
         <script src="/vendors/bootstrap/bootstrap.bundle.min.js"></script>
    <script src="/vendors/marked/marked.min.js"></script>
    <script src="/vendors/highlightjs/highlight.min.js"></script>
    <link rel="stylesheet" href="/vendors/highlightjs/github.min.css">
 </head>
 <body>
     <!-- 引入统一导航栏 -->
     <div th:replace="~{fragments/navbar :: navbar('chat')}"></div>
     
     <!-- 主聊天应用 -->
     <div class="chat-app">
        <!-- 左侧对话列表 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <div class="sidebar-title">对话</div>
                <div class="sidebar-subtitle">共 <span id="chat-count">1</span> 个对话</div>
                <button class="new-chat-btn" onclick="createNewChat()">
                    ➕ 新建对话
                </button>
            </div>
            
            <div class="chat-list" id="chat-list">
                <div class="chat-item active" data-chat-id="default">
                    <div class="chat-item-title">未命名对话</div>
                    <div class="chat-item-preview">开始新的对话...</div>
                    <div class="chat-item-time">刚刚</div>
                </div>
            </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="chat-main">


                         <div class="chat-messages" id="chat-messages">
                 <!-- 欢迎界面 -->
                 <div class="welcome-container" id="welcome-container">
                     <div class="welcome-icon">
                         <i class="fas fa-robot"></i>
                     </div>
                     <h1 class="welcome-title">欢迎使用AI智能助手</h1>
                     <p class="welcome-subtitle">
                         我是您的专业求职顾问，可以为您提供面试指导、职业规划等全方位的求职服务。
                         让我们开始对话，助您找到理想的工作机会！
                     </p>
                     <div class="welcome-features">
                         <div class="feature-item">
                             <div class="feature-icon">
                                 <i class="fas fa-user-tie"></i>
                             </div>
                             <div class="feature-title">面试指导</div>
                             <div class="feature-description">模拟面试场景，提供专业的面试技巧和建议</div>
                         </div>
                         <div class="feature-item">
                             <div class="feature-icon">
                                 <i class="fas fa-file-upload"></i>
                             </div>
                                                            <div class="feature-title">文件分析</div>
                             <div class="feature-description">点击📎按钮上传文件，我可以帮您分析文档、图片等各种文件</div>
                         </div>
                         <div class="feature-item">
                             <div class="feature-icon">
                                 <i class="fas fa-chart-line"></i>
                             </div>
                             <div class="feature-title">职业规划</div>
                             <div class="feature-description">制定个性化的职业发展路径和目标</div>
                         </div>
                         <div class="feature-item">
                             <div class="feature-icon">
                                 <i class="fas fa-lightbulb"></i>
                             </div>
                             <div class="feature-title">求职建议</div>
                             <div class="feature-description">提供行业洞察和求职策略指导</div>
                         </div>
                     </div>
                 </div>

                <!-- 打字指示器 -->
                <div class="message ai" style="display: none;">
                    <div class="message-avatar">🤖</div>
                    <div class="typing-indicator" id="typing-indicator">
                        <div class="typing-dots">
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                        </div>
                        <span class="typing-text">智能助手正在思考中...</span>
                    </div>
                </div>
            </div>

            <div class="chat-input">
                <div class="input-container">
                    <!-- 文件上传区域 -->
                    <div class="file-upload-area" id="file-upload-area" style="display: none;">
                        <div class="file-preview" id="file-preview">
                            <div class="file-info">
                                <i class="fas fa-file-alt file-icon"></i>
                                <div class="file-details">
                                    <span class="file-name" id="file-name">未选择文件</span>
                                    <span class="file-size" id="file-size"></span>
                                </div>
                                <button class="remove-file-btn" id="remove-file-btn" onclick="removeFile()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>

                    </div>
                    
                    <!-- 输入框和按钮区域 -->
                    <div class="input-row">
                        <input type="file" id="file-input" accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.gif,.bmp" style="display: none;" onchange="handleFileSelect(event)">
                        <button class="attachment-btn" id="attachment-btn" onclick="document.getElementById('file-input').click()" title="上传文件">
                            <i class="fas fa-paperclip"></i>
                        </button>
                        <textarea 
                            id="message-input" 
                            class="message-input" 
                            placeholder="请输入对话内容...（Shift+Enter换行，Enter发送）" 
                            rows="1"></textarea>
                        <button id="send-button" class="send-button" onclick="sendMessage()">
                            ➤
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentUser = null;
        let messageCount = 0;
        let currentChatId = 'default';
        let chatSessions = {
            'default': {
                id: 'default',
                title: '未命名对话',
                messages: [],
                lastMessage: '开始新的对话...',
                time: '刚刚'
            }
        };

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeMarkdown();
            checkLoginStatus();
            setupEventListeners();
            loadChatSessions();
        });

        // 初始化Markdown解析器
        function initializeMarkdown() {
            // 配置marked
            if (typeof marked !== 'undefined') {
                marked.setOptions({
                    highlight: function(code, lang) {
                        if (typeof hljs !== 'undefined' && lang && hljs.getLanguage(lang)) {
                            try {
                                return hljs.highlight(code, { language: lang }).value;
                            } catch (err) {}
                        }
                        return code;
                    },
                    breaks: true,
                    gfm: true
                });
            }

            // 初始化代码高亮
            if (typeof hljs !== 'undefined') {
                hljs.configure({
                    languages: ['javascript', 'python', 'java', 'html', 'css', 'sql', 'json', 'xml', 'bash']
                });
            }
        }

        // 为代码块添加复制按钮
        function addCopyButtonsToCodeBlocks(container) {
            const codeBlocks = container.querySelectorAll('pre');
            codeBlocks.forEach(pre => {
                // 创建包装器
                const wrapper = document.createElement('div');
                wrapper.className = 'code-block-wrapper';
                
                // 创建复制按钮
                const copyBtn = document.createElement('button');
                copyBtn.className = 'copy-code-btn';
                copyBtn.textContent = '复制';
                copyBtn.onclick = function() {
                    const code = pre.querySelector('code');
                    const text = code ? code.textContent : pre.textContent;
                    
                    navigator.clipboard.writeText(text).then(() => {
                        copyBtn.textContent = '已复制';
                        setTimeout(() => {
                            copyBtn.textContent = '复制';
                        }, 2000);
                    }).catch(err => {
                        console.error('复制失败:', err);
                        // 降级方案
                        const textArea = document.createElement('textarea');
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        document.execCommand('copy');
                        document.body.removeChild(textArea);
                        
                        copyBtn.textContent = '已复制';
                        setTimeout(() => {
                            copyBtn.textContent = '复制';
                        }, 2000);
                    });
                };
                
                // 包装代码块
                pre.parentNode.insertBefore(wrapper, pre);
                wrapper.appendChild(pre);
                wrapper.appendChild(copyBtn);
            });
        }

        // 检查登录状态
        function checkLoginStatus() {
            if (window.authManager) {
                const userInfo = window.authManager.getCurrentUser();
                if (userInfo.isLoggedIn) {
                    currentUser = userInfo.username;
                } else {
                    currentUser = 'anonymous_user';
                }
            } else {
                // 兼容性处理
                const username = localStorage.getItem('username');
                const token = localStorage.getItem('token');

                if (username && token) {
                    currentUser = username;
                } else {
                    currentUser = 'anonymous_user';
                }
            }
        }

        // 设置事件监听器
        function setupEventListeners() {
            const messageInput = document.getElementById('message-input');
            
            // 回车发送消息
            messageInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // 自动调整文本域高度
            messageInput.addEventListener('input', function() {
                this.style.height = 'auto';
                const newHeight = Math.min(Math.max(this.scrollHeight, 44), 120);
                this.style.height = newHeight + 'px';
            });
        }



        // 加载聊天会话
        async function loadChatSessions() {
            try {
                if (currentUser && currentUser !== 'anonymous_user') {
                    // 登录用户：从后端加载会话列表
                    const response = await fetch(`/chat/sessions?username=${encodeURIComponent(currentUser)}`);
                    if (response.ok) {
                        const data = await response.json();
                        if (data.success && data.sessions && data.sessions.length > 0) {
                            chatSessions = {};
                            data.sessions.forEach(session => {
                                chatSessions[session.id] = {
                                    id: session.id,
                                    title: session.title,
                                    messages: [], // 消息将按需加载
                                    lastMessage: session.title,
                                    time: formatTime(session.lastMessageTime || session.createTime),
                                    loaded: false // 标记消息是否已加载
                                };
                            });
                            
                            // 设置当前会话为最新的会话
                            const sessionIds = Object.keys(chatSessions);
                            currentChatId = sessionIds[0];
                        } else {
                            createDefaultSession();
                        }
                    } else {
                        createDefaultSession();
                    }
                } else {
                    // 匿名用户：只使用本地存储，不调用后端接口
                    const savedSessions = localStorage.getItem('anonymousChatSessions');

                    if (savedSessions) {
                        try {
                            chatSessions = JSON.parse(savedSessions);

                            // 验证数据完整性
                            if (!chatSessions || Object.keys(chatSessions).length === 0) {

                                createDefaultSession();
                            } else {
                                // 设置当前会话为第一个会话
                                const sessionIds = Object.keys(chatSessions);
                                currentChatId = sessionIds[0];

                            }
                        } catch (e) {
                            console.error('解析本地会话数据失败:', e);
                            createDefaultSession();
                        }
                    } else {

                        createDefaultSession();
                    }
                }
                updateChatList();
            } catch (error) {
                console.error('加载会话失败:', error);
                createDefaultSession();
                updateChatList();
            }
        }

        // 创建默认会话
        function createDefaultSession() {
            chatSessions = {
                'default': {
                    id: 'default',
                    title: '未命名对话',
                    messages: [],
                    lastMessage: '开始新的对话...',
                    time: '刚刚',
                    loaded: true
                }
            };
            currentChatId = 'default';
        }

        // 格式化时间
        function formatTime(timeString) {
            if (!timeString) return '刚刚';
            
            const time = new Date(timeString);
            const now = new Date();
            const diffMs = now - time;
            const diffMins = Math.floor(diffMs / 60000);
            const diffHours = Math.floor(diffMs / 3600000);
            const diffDays = Math.floor(diffMs / 86400000);
            
            if (diffMins < 1) return '刚刚';
            if (diffMins < 60) return `${diffMins}分钟前`;
            if (diffHours < 24) return `${diffHours}小时前`;
            if (diffDays < 7) return `${diffDays}天前`;
            
            return time.toLocaleDateString('zh-CN', { 
                month: 'short', 
                day: 'numeric' 
            });
        }

        // 创建新对话
        async function createNewChat() {
            try {
                // 为匿名用户和登录用户创建不同类型的会话
                const newChatId = (currentUser === 'anonymous_user' || !currentUser) ? 
                    'anon_' + Date.now() : 'temp_' + Date.now();
                
                const newChat = {
                    id: newChatId,
                    title: '新对话',
                    messages: [],
                    lastMessage: '开始新的对话...',
                    time: '刚刚',
                    loaded: true,
                    isTemp: currentUser !== 'anonymous_user' && currentUser // 只有登录用户的会话才标记为临时
                };
                
                chatSessions[newChatId] = newChat;
                currentChatId = newChatId;
                
                updateChatList();
                clearChatMessages();
                showWelcome();
                
                // 匿名用户立即保存会话
                if (currentUser === 'anonymous_user' || !currentUser) {
                    saveChatSessions();
                }
                

            } catch (error) {
                console.error('创建新对话失败:', error);
            }
        }

        // 切换对话
        async function switchChat(chatId) {
            if (currentChatId === chatId) return;
            
            
            
            currentChatId = chatId;
            updateChatList();
            await loadChatMessages(chatId);
        }

        // 加载对话消息
        async function loadChatMessages(chatId) {
            const session = chatSessions[chatId];
            if (!session) return;
            
            clearChatMessages();
            
            try {
                // 匿名用户：直接显示本地保存的消息
                if (currentUser === 'anonymous_user' || !currentUser) {
                    if (session.messages && session.messages.length > 0) {
                        hideWelcome();
                        session.messages.forEach(msg => {
                            addMessageToUI(msg.type, msg.content, false);
                        });

                    } else {
                        showWelcome();

                    }
                    return;
                }
                
                // 登录用户：处理临时会话和已加载的会话
                if (session.isTemp || session.loaded) {
                    if (session.messages.length === 0) {
                        showWelcome();
                    } else {
                        hideWelcome();
                        session.messages.forEach(msg => {
                            addMessageToUI(msg.type, msg.content, false);
                        });
                    }
                    return;
                }
                
                // 登录用户：从后端加载消息历史
                if (currentUser && currentUser !== 'anonymous_user' && !session.isTemp) {
                    const response = await fetch(`/chat/sessions/${chatId}/messages?username=${encodeURIComponent(currentUser)}`);
                    if (response.ok) {
                        const data = await response.json();
                        if (data.success && data.messages) {
                            session.messages = data.messages.map(msg => ({
                                type: msg.messageType,
                                content: msg.content,
                                time: msg.createTime
                            }));
                            session.loaded = true;
                            
                            if (session.messages.length === 0) {
                                showWelcome();
                            } else {
                                hideWelcome();
                                session.messages.forEach(msg => {
                                    addMessageToUI(msg.type, msg.content, false);
                                });
                            }
                        } else {
                            showWelcome();
                        }
                    } else {
                        console.error('加载消息失败:', response.status);
                        showWelcome();
                    }
                } else {
                    showWelcome();
                }
            } catch (error) {
                console.error('加载对话消息失败:', error);
                showWelcome();
            }
        }

        // 清空聊天消息
        function clearChatMessages() {
            const messagesContainer = document.getElementById('chat-messages');
            const messages = messagesContainer.querySelectorAll('.message');
            messages.forEach(msg => msg.remove());
        }

                 // 显示欢迎界面
         function showWelcome() {
             const welcomeDiv = document.getElementById('welcome-container');
             if (welcomeDiv) {
                 welcomeDiv.style.display = 'flex';
             }
         }

         // 隐藏欢迎界面
         function hideWelcome() {
             const welcomeDiv = document.getElementById('welcome-container');
             if (welcomeDiv) {
                 welcomeDiv.style.display = 'none';
             }
         }

        // 保存聊天会话
        function saveChatSessions() {
            // 只为匿名用户保存到本地存储
            if (!currentUser || currentUser === 'anonymous_user') {
                localStorage.setItem('anonymousChatSessions', JSON.stringify(chatSessions));

            }
            // 登录用户的会话会自动保存到数据库
        }

        // 发送建议问题
        function sendSuggestedQuestion(question) {
            document.getElementById('message-input').value = question;
            sendMessage();
        }

        // 发送消息（修改版）
        async function sendMessage() {
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const message = messageInput.value.trim();

            if (!message) {
                return;
            }

            // 隐藏欢迎界面
            hideWelcome();

            // 禁用输入和按钮
            messageInput.disabled = true;
            sendButton.disabled = true;
            sendButton.innerHTML = '⏳';

            // 显示用户消息
            addMessageToUI('user', message, true);
            messageInput.value = '';
            messageInput.style.height = '44px';

            // 显示打字指示器
            showTypingIndicator();
            
            // 添加处理进度提示
            let progressTimer = setTimeout(() => {
                updateTypingIndicator('智能助手正在深度思考中...');
            }, 10000); // 10秒后显示深度思考提示
            
            let longProcessTimer = setTimeout(() => {
                updateTypingIndicator('正在处理复杂问题，请耐心等待...');
            }, 30000); // 30秒后显示复杂问题提示

            try {

                
                // 创建超时控制器 - 增加到2分钟
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 120000);
                
                const requestBody = {
                    message: message,
                    username: currentUser
                };

                
                const response = await fetch('/chat/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody),
                    signal: controller.signal
                });

                clearTimeout(timeoutId);


                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                // 清理进度定时器
                clearTimeout(progressTimer);
                clearTimeout(longProcessTimer);
                
                // 隐藏打字指示器
                hideTypingIndicator();

                if (data.success) {
                    // 显示AI回复

                    addMessageToUI('ai', data.message, true);
                    
                    // 更新对话标题（如果是新对话的第一条消息）
                    await updateChatTitle(message);
                    
                    // 如果是登录用户，重新加载会话列表以获取最新状态
                    if (currentUser && currentUser !== 'anonymous_user') {
                        await loadChatSessions();
                    }
                } else {
                    // 显示错误消息
                    addErrorMessage(data.error || '发送消息失败，请重试');
                }

            } catch (error) {
                console.error('发送消息失败:', error);
                
                // 清理进度定时器
                clearTimeout(progressTimer);
                clearTimeout(longProcessTimer);
                
                hideTypingIndicator();
                
                let errorMessage = '网络错误，请检查连接后重试';
                if (error.name === 'AbortError') {
                    errorMessage = '请求超时，请稍后重试';
                } else if (error.message.includes('404')) {
                    errorMessage = '服务接口不存在，请联系管理员';
                } else if (error.message.includes('500')) {
                    errorMessage = '服务器内部错误，请稍后重试';
                }
                
                addErrorMessage(errorMessage);
            } finally {
                // 恢复输入和按钮
                messageInput.disabled = false;
                sendButton.disabled = false;
                sendButton.innerHTML = '➤';
                messageInput.focus();
            }
        }

        // 更新对话标题
        async function updateChatTitle(firstMessage) {
            const session = chatSessions[currentChatId];
            if (session && session.messages.length <= 2) { // 第一轮对话
                const title = firstMessage.length > 20 ? firstMessage.substring(0, 20) + '...' : firstMessage;
                session.title = title;
                
                // 如果是临时会话，转换为正式会话
                if (session.isTemp) {
                    // 临时会话会在后端自动创建，这里只需要更新本地状态
                    session.isTemp = false;
                }
                
                saveChatSessions();
                updateChatList();
            }
        }

        // 添加错误消息
        function addErrorMessage(content) {
            try {
                const messagesContainer = document.getElementById('chat-messages');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message ai';

                const avatarDiv = document.createElement('div');
                avatarDiv.className = 'message-avatar';
                avatarDiv.textContent = '⚠️';

                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content error-message';
                contentDiv.textContent = content;

                messageDiv.appendChild(avatarDiv);
                messageDiv.appendChild(contentDiv);
                messagesContainer.appendChild(messageDiv);
                
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            } catch (error) {
                console.error('添加错误消息失败:', error);
            }
        }

        // 显示打字指示器
        function showTypingIndicator() {
            try {
                const typingIndicator = document.getElementById('typing-indicator');
                if (typingIndicator) {
                    typingIndicator.style.display = 'flex';
                    
                    // 重置文本为默认状态
                    const messageSpan = typingIndicator.querySelector('.typing-text');
                    if (messageSpan) {
                        messageSpan.textContent = '智能助手正在思考中...';
                    }
                    
                    const messagesContainer = document.getElementById('chat-messages');
                    if (messagesContainer) {
                        messagesContainer.scrollTop = messagesContainer.scrollHeight;
                    }
                }
            } catch (error) {
                console.error('显示打字指示器失败:', error);
            }
        }

        // 隐藏打字指示器
        function hideTypingIndicator() {
            try {
                const typingIndicator = document.getElementById('typing-indicator');
                if (typingIndicator) {
                    typingIndicator.style.display = 'none';
                }
            } catch (error) {
                console.error('隐藏打字指示器失败:', error);
            }
        }

        // 更新打字指示器文本
        function updateTypingIndicator(message) {
            try {
                const typingIndicator = document.getElementById('typing-indicator');
                if (typingIndicator) {
                    const messageSpan = typingIndicator.querySelector('.typing-text');
                    if (messageSpan) {
                        messageSpan.textContent = message;
                    }
                }
            } catch (error) {
                console.error('更新打字指示器失败:', error);
            }
        }

        // 更新聊天列表
        function updateChatList() {
            const chatList = document.getElementById('chat-list');
            const chatCount = document.getElementById('chat-count');
            
            chatList.innerHTML = '';
            const sessions = Object.values(chatSessions);
            
            sessions.forEach(session => {
                const chatItem = document.createElement('div');
                chatItem.className = `chat-item ${session.id === currentChatId ? 'active' : ''}`;
                chatItem.setAttribute('data-chat-id', session.id);
                chatItem.onclick = () => switchChat(session.id);
                
                chatItem.innerHTML = `
                    <div class="chat-item-title">${session.title}</div>
                    <div class="chat-item-preview">${session.lastMessage}</div>
                    <div class="chat-item-time">${session.time}</div>
                    <div class="chat-item-delete" onclick="deleteChat('${session.id}', event)" title="删除对话">🗑️</div>
                `;
                
                chatList.appendChild(chatItem);
            });
            
            chatCount.textContent = sessions.length;
        }

        // 添加消息到UI
        function addMessageToUI(type, content, saveToSession = true) {
            try {

                
                const messagesContainer = document.getElementById('chat-messages');
                if (!messagesContainer) {
                    console.error('找不到消息容器元素');
                    return;
                }

                // 如果是第一条用户消息，隐藏欢迎界面
                if (type === 'user') {
                    const welcomeContainer = document.getElementById('welcome-container');
                    if (welcomeContainer && welcomeContainer.style.display !== 'none') {
                        welcomeContainer.style.display = 'none';
                        messagesContainer.classList.add('has-messages');
                    }
                }

                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${type}`;

                const avatarDiv = document.createElement('div');
                avatarDiv.className = 'message-avatar';
                avatarDiv.textContent = type === 'user' ? (currentUser && currentUser[0] ? currentUser[0].toUpperCase() : 'U') : '🤖';

                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content';
                
                // AI消息使用Markdown渲染，用户消息使用纯文本
                if (type === 'ai' && typeof marked !== 'undefined') {
                    try {
                        const htmlContent = marked.parse(content || '消息内容为空');
                        contentDiv.innerHTML = htmlContent;
                        
                        // 为代码块添加复制按钮
                        addCopyButtonsToCodeBlocks(contentDiv);
                        
                        // 高亮代码块
                        if (typeof hljs !== 'undefined') {
                            contentDiv.querySelectorAll('pre code').forEach((block) => {
                                hljs.highlightElement(block);
                            });
                        }
                    } catch (error) {
                        console.error('Markdown解析失败:', error);
                        contentDiv.textContent = content || '消息内容为空';
                    }
                } else {
                    contentDiv.textContent = content || '消息内容为空';
                }

                const timeDiv = document.createElement('div');
                timeDiv.className = 'message-time';
                timeDiv.textContent = new Date().toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });

                if (type === 'user') {
                    messageDiv.appendChild(contentDiv);
                    messageDiv.appendChild(avatarDiv);
                } else {
                    messageDiv.appendChild(avatarDiv);
                    messageDiv.appendChild(contentDiv);
                }

                contentDiv.appendChild(timeDiv);
                messagesContainer.appendChild(messageDiv);
                
                // 滚动到底部
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
                messageCount++;

                // 保存到会话
                if (saveToSession) {
                    const session = chatSessions[currentChatId];
                    if (session) {
                        session.messages.push({
                            type: type,
                            content: content,
                            time: new Date().toISOString()
                        });
                        
                        // 更新最后消息预览
                        const safeContent = content || '';
                        session.lastMessage = safeContent.length > 30 ? safeContent.substring(0, 30) + '...' : safeContent;
                        session.time = new Date().toLocaleTimeString('zh-CN', { 
                            hour: '2-digit', 
                            minute: '2-digit' 
                        });
                        
                        saveChatSessions();
                        updateChatList();
                    }
                }
                
                
            } catch (error) {
                console.error('添加消息失败:', error);
            }
        }

        // 删除对话
        async function deleteChat(chatId, event) {
            if (event) {
                event.stopPropagation(); // 阻止事件冒泡
            }
            
            if (!confirm('确定要删除这个对话吗？')) {
                return;
            }
            
            try {
                if (currentUser && currentUser !== 'anonymous_user' && !chatSessions[chatId]?.isTemp) {
                    // 登录用户：调用后端API删除
                    const response = await fetch(`/chat/sessions/${chatId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        if (data.success) {
    
                        }
                    }
                }
                
                // 删除本地会话
                delete chatSessions[chatId];
                
                // 如果删除的是当前会话，切换到其他会话
                if (currentChatId === chatId) {
                    const remainingSessions = Object.keys(chatSessions);
                    if (remainingSessions.length > 0) {
                        currentChatId = remainingSessions[0];
                        await loadChatMessages(currentChatId);
                    } else {
                        // 没有其他会话，创建新的默认会话
                        createDefaultSession();
                        clearChatMessages();
                        showWelcome();
                    }
                }
                
                updateChatList();
                saveChatSessions();
                
            } catch (error) {
                console.error('删除对话失败:', error);
                alert('删除对话失败，请重试');
            }
        }


    </script>
    
    <!-- 认证管理脚本 -->
    <script src="/js/auth.js"></script>
    <script src="/js/page-auth.js"></script>
    
    <script>
        // 文件处理相关变量
        let selectedFile = null;
        let uploadedFileId = null;

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            // 检查文件类型
            const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'];
            if (!allowedTypes.includes(file.type)) {
                alert('请选择PDF、DOC、DOCX或TXT格式的文件');
                return;
            }

            // 检查文件大小（限制10MB）
            if (file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB');
                return;
            }

            selectedFile = file;
            showFilePreview(file);
        }

        // 显示文件预览
        function showFilePreview(file) {
            const fileUploadArea = document.getElementById('file-upload-area');
            const fileName = document.getElementById('file-name');
            const fileSize = document.getElementById('file-size');
            const fileIcon = document.querySelector('.file-icon');
            const attachmentBtn = document.getElementById('attachment-btn');

            // 根据文件类型设置图标
            if (file.type.includes('pdf')) {
                fileIcon.className = 'fas fa-file-pdf file-icon';
                fileIcon.style.color = '#dc2626';
            } else if (file.type.includes('word') || file.type.includes('document')) {
                fileIcon.className = 'fas fa-file-word file-icon';
                fileIcon.style.color = '#2563eb';
            } else {
                fileIcon.className = 'fas fa-file-alt file-icon';
                fileIcon.style.color = '#3b82f6';
            }

            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            fileUploadArea.style.display = 'flex';

            // 更新附件按钮状态
            attachmentBtn.classList.add('has-file');
            attachmentBtn.innerHTML = '<i class="fas fa-file-check"></i>';
            attachmentBtn.title = '已选择文件: ' + file.name;

            // 更新输入框提示
            const messageInput = document.getElementById('message-input');
            messageInput.placeholder = '已选择文件，可以直接发送或输入问题...';
        }

        // 移除文件
        function removeFile() {
            selectedFile = null;
            uploadedFileId = null;
            
            const fileUploadArea = document.getElementById('file-upload-area');
            const messageInput = document.getElementById('message-input');
            const fileInput = document.getElementById('file-input');
            const attachmentBtn = document.getElementById('attachment-btn');
            
            fileUploadArea.style.display = 'none';
            messageInput.placeholder = '请输入对话内容...（Shift+Enter换行，Enter发送）';
            fileInput.value = '';
            
            // 重置附件按钮状态
            attachmentBtn.classList.remove('has-file');
            attachmentBtn.innerHTML = '<i class="fas fa-paperclip"></i>';
            attachmentBtn.title = '上传文件';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }



        // 发送带文件的消息
        async function sendMessageWithFile(message = null) {
            if (!selectedFile) {
                // 如果没有文件，按正常流程发送
                return sendMessage();
            }

            const messageInput = document.getElementById('message-input');
            const userMessage = message || messageInput.value.trim();
            
            // 添加用户消息到UI（包含文件信息）
            let displayMessage = userMessage || '请帮我分析这个文件';
            displayMessage += `\n📎 ${selectedFile.name}`;
            addMessageToUI('user', displayMessage);
            
            // 清空输入框
            messageInput.value = '';
            messageInput.style.height = '44px';

            try {
                // 显示上传进度
                showTypingIndicator();
                updateTypingIndicator('正在上传文件...');

                // 创建FormData
                const formData = new FormData();
                formData.append('file', selectedFile);
                formData.append('message', userMessage || '');
                formData.append('username', currentUser);

                // 发送请求到新的文件上传接口
                const response = await fetch('/chat/send-with-file', {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    const data = await response.json();
                    
                    if (data.success) {
                        // 添加AI回复
                        addMessageToUI('ai', data.message);
                        
                        // 更新会话标题（如果是新对话的第一条消息）
                        const session = chatSessions[currentChatId];
                        if (session && session.messages.length <= 2 && session.title === '未命名对话') {
                            const titleText = userMessage || `文件分析：${selectedFile.name}`;
                            session.title = titleText.length > 20 ? titleText.substring(0, 20) + '...' : titleText;
                            updateChatList();
                        }
                        
                        // 如果是登录用户，重新加载会话列表以获取最新状态
                        if (currentUser && currentUser !== 'anonymous_user') {
                            await loadChatSessions();
                        }
                        
                        // 清理文件选择
                        removeFile();
                    } else {
                        addErrorMessage(data.error || data.message || '文件发送失败，请稍后再试');
                    }
                } else {
                    addErrorMessage('网络错误，请检查网络连接后重试');
                }

            } catch (error) {
                console.error('发送带文件消息失败:', error);
                addErrorMessage('发送失败，请稍后再试');
            } finally {
                hideTypingIndicator();
            }
        }

        // 修改原有的sendMessage函数，支持文件发送
        async function sendMessage() {
            // 如果有选中的文件，使用文件发送功能
            if (selectedFile) {
                return sendMessageWithFile();
            }

            const messageInput = document.getElementById('message-input');
            const message = messageInput.value.trim();
            
            if (!message) {
                return;
            }

            // 添加用户消息到UI
            addMessageToUI('user', message);
            messageInput.value = '';
            messageInput.style.height = '44px';

            // 显示打字指示器
            showTypingIndicator();

            try {
                const response = await fetch('/chat/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        username: currentUser,
                        conversationId: currentChatId
                    })
                });

                if (response.ok) {
                    const data = await response.json();

                    
                    if (data.success) {
                        // 添加AI回复 - 修复字段名从response改为message
                        addMessageToUI('ai', data.message);
                        
                        // 更新会话标题（如果是新会话的第一条消息）
                        const session = chatSessions[currentChatId];
                        if (session && session.messages.length <= 2 && session.title === '未命名对话') {
                            session.title = message.length > 20 ? message.substring(0, 20) + '...' : message;
                            updateChatList();
                        }
                    } else {
                        addErrorMessage(data.error || data.message || '发送失败，请稍后再试');
                    }
                } else {
                    addErrorMessage('网络错误，请检查网络连接后重试');
                }

            } catch (error) {
                console.error('发送消息失败:', error);
                addErrorMessage('发送失败，请稍后再试');
            } finally {
                hideTypingIndicator();
            }
        }
    </script>
</body>
</html> 